package com.csii.activiti.server.api;

import com.csii.activiti.server.api.vo.FileResult;
import com.csii.activiti.server.api.vo.FileResultData;
import com.csii.activiti.server.core.exception.RequestParamException;
import com.csii.activiti.server.core.utils.IdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Api(tags="文件接口")
@RestController
@RequestMapping("/${activity.basic.url:activiti}/file")
@Slf4j
public class FlowFileController {

    @Value("${activity.upload.path:file/}")
    private String uploadPath;

    @Value("${activity.upload.localhost:http://localhost:8765}")
    private String localhost;

    @Value("${activity.basic.url:activiti}")
    private String prefixPath;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    @CrossOrigin
    public FileResult upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            throw new RequestParamException("上传失败，请选择文件");
        }

        String fileName = file.getOriginalFilename();
        fileName = IdUtils.getId() + fileName.substring(fileName.indexOf("."));

        String path = new File(uploadPath).getAbsolutePath();
        String saveFilePath = path + "/"+fileName;
        File dest = new File(saveFilePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            return new FileResult(0,new FileResultData(localhost +"/"+prefixPath+"/file/download/"+ fileName));
        } catch (IOException e) {
            log.error(e.toString(), e);
            throw new RequestParamException("上传失败",e);
        }
    }

    @ApiOperation("文件下载")
    @GetMapping("/download/**")
    @CrossOrigin
    public void download(HttpServletRequest request, HttpServletResponse response){
        String filePath = new String(extractPathFromPattern(request));
        File file = new File(new File(uploadPath).getAbsolutePath() +"/"+ filePath);
        InputStream inputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(file));
            response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"),"iso-8859-1"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        OutputStream outputStream = null;
        if (inputStream != null){
            response.setContentType("multipart/form-data");
            try {
                outputStream = response.getOutputStream();
                if(inputStream != null){
                    byte[] buf = new byte[1024*1024*3];
                    int len;
                    while ((len = inputStream.read(buf)) > 0) {
                        outputStream.write(buf, 0, len);
                    }
                    response.flushBuffer();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (outputStream != null){
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (inputStream != null){
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 把指定URL后的字符串全部截断当成参数
     * 这么做是为了防止URL中包含中文或者特殊字符（/等）时，匹配不了的问题
     *
     * @param request
     * @return
     */
    private static String extractPathFromPattern(final HttpServletRequest request) {
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
    }
}
